#!/usr/bin/perl -w

# Copyright 2011 David Rathbun (proqservers.net, proqstudios.net)
# Other Credits:
# Code samples: Evan Hoffman (evanhoffman.com)
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#      http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# This patch file is for AmazonSES PERL script "ses-send-email.pl"
#


# Tips from the author:
# Lines end with (0x0D, 0x0A) the same as '\r\n'. Failure to abide by this
# will cause AmazonSES to reject mail completely.
#
# This is coded with intention to use with POSTFIX and Virtualmin defaults.
# Usage with a combination of SendMail, cPanel, or Plesk may require
# additional modifications.

package ses-patch;

our $VERSION = '0.08';
require Exporter;
@ISA = qw(Exporter);
@EXPORT_OK = qw(patch_this); # symbols to export on request

use MIME::Base64;
use File::Path qw(make_path);
use Digest::MD5 qw(md5 md5_hex md5_base64);
use Switch;

use FindBin;
use lib "$FindBin::Bin/patch";
use patch-conf;
use patch-content;
use patch-headers;
use patch-atts;

my $mail_header = "";
my $mail_body = "";
my $mail_final = "";

sub patch_this {
	my $prep_line = "";
	my $in_header = 1;
	my $in_body = 0;
	$mail_header = "";
	$mail_body = "";
	$mail_final = "";
	
	if ($_[0]) {
		# Passing entire mail
	} else {
		# Passing STDIN
		while (<STDIN>) {
			patch_from($_);
		}
	}
	
	# DO NOT MESS WITH ORDER
	
	switch ($patch_headers){
		case 0 {$mail_header = patch_header_0($mail_header)}
		case 1 {$mail_header = patch_header_1($mail_header)}
		case 2 {$mail_header = patch_header_2($mail_header)}
		case 255 {$mail_header = patch_header_255($mail_header)}
	}
	
	switch ($patch_content){
		case 0 {$mail_body = patch_content_0($mail_body)}
		case 1 {$mail_body = patch_content_1($mail_body)}
		case 2 {$mail_body = patch_content_2($mail_body)}
		case 255 {$mail_body = patch_content_255($mail_body)}
	}
	
	switch ($patch_atts){
		case 0 {$mail_body = patch_atts_0($mail_body)}
		case 1 {$mail_body = patch_atts_1($mail_body)}
		case 2 {$mail_body = patch_atts_2($mail_body)}
		case 255 {$mail_body = patch_atts_255($mail_body)}
	}
	
	$mail_final = $mail_header . $mail_body;
	
	return $mail_final;
}

sub patch_from {
		my $prep_line = $_[0];
		# Two linebreaks between header & body
        if ($in_header && ($prep_line =~ /^[\r\n]/)) {
			$in_header = 0;
			$in_body = 1;
        }
		if ($in_header) {
			$mail_header .= $prep_line;
		}
		if ($in_body) {
			$mail_body .= $prep_line;
		}
}